package com.flyme.module.base.provider.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.flyme.common.core.model.ResultBody;
import com.flyme.common.core.model.query.CriteriaQuery;
import com.flyme.common.core.model.query.PagerInfo;
import com.flyme.common.core.model.query.PqGrid;
import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.core.base.supper.controller.BaseController;
import com.flyme.core.base.supper.entity.EntityMap;
import com.flyme.module.base.client.entity.SysUser;
import com.flyme.module.base.provider.service.SysExaminationService;
import com.flyme.module.base.provider.service.SysLecturerService;
import com.flyme.module.base.provider.service.SysUserService;
import com.flyme.module.file.provider.service.SysCataLogService;
import com.flyme.module.order.client.entity.Order;
import com.flyme.module.order.client.enums.OrderTypeEnum;
import com.flyme.module.order.client.enums.PayStatusEnum;
import com.flyme.module.order.provider.service.OrderService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * 首页统计
 *
 * @author zyf
 */
@Api(tags = "首页统计")
@RestController
public class HomeReportController extends BaseController<SysUserService, SysUser> {


    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private OrderService orderService;
    @Autowired
    private SysCataLogService cataLogService;
    @Autowired
    private SysLecturerService lecturerService;
    @Autowired
    private SysExaminationService examinationService;


    @PostMapping("/home/report")
    public ResultBody report() {
        Map<String, Object> map = new HashMap<>();
        //今日注册用户数量
        Integer userCountByToday = sysUserService.count(q().eq("userType", "UT_STUDENT").ge("createTime", DateUtil.date()));
        map.put("userCountByToday", userCountByToday);
        //用户总数量
        Integer userCount = sysUserService.count(q().eq("userType", "UT_STUDENT"));
        map.put("userCount", userCount);

        QueryWrapper o1 = new QueryWrapper<Order>();
        //今日订单合计
        o1.select("count(id) orderCountToday", "coalesce(sum(orderAmount),0) orderAmountToday");
        o1.ge(true, "createTime", DateUtil.date());
        o1.eq("payStatus", PayStatusEnum.PAY);
        Map<String, Object> orderMap = orderService.getMap(o1);
        map.putAll(orderMap);
        //订单总合计
        QueryWrapper o2 = new QueryWrapper<Order>();
        o2.select("count(id) orderCount", "coalesce(sum(orderAmount),0) orderAmount");
        o2.eq("payStatus", PayStatusEnum.PAY);
        Map<String, Object> orderMapTotal = orderService.getMap(o2);
        map.putAll(orderMapTotal);


        //订单总合计
        CriteriaQuery o3 = new CriteriaQuery<Order>();
        o3.select("max(orderBody) name", "coalesce(count(targetId),0) total");
        o3.eq("payStatus", PayStatusEnum.PAY);
        o3.eq("orderEntity", OrderTypeEnum.course);
        o3.groupBy("targetId");
        o3.orderByDesc("count(targetId)");
        List list = orderService.listEntityMaps(o3);
        map.put("courseList", list);

        //7日销售额
        List<EntityMap> list2 = orderService.getSevenSale();

        List<String> sale_dates = new ArrayList<>();
        List<Integer> sale_nums = new ArrayList<>();
        List<BigDecimal> sale_amounts = new ArrayList<>();
        Date now = DateUtil.offsetDay(DateUtil.date(), -7);
        for (int i = 1; i <= 7; i++) {
            Date d = DateUtil.offset(now, DateField.DAY_OF_MONTH, i);
            String date = DateUtil.format(d, "yyyy-MM-dd");
            sale_dates.add(date);
            Boolean tag = false;
            for (EntityMap entityMap : list2) {
                Date saleDate = entityMap.get("saleDate");
                if (date.equals(saleDate.toString())) {
                    Long num = entityMap.get("orderNum");
                    sale_nums.add(num.intValue());
                    sale_amounts.add(entityMap.get("orderAmount"));
                    tag = true;
                }
            }
            if (!tag) {
                sale_nums.add(0);
                sale_amounts.add(new BigDecimal("0"));
            }
        }
        //7日用户注册量
        List<EntityMap> list3 = sysUserService.getSevenSale("UT_STUDENT");
        List<Integer> user_nums = new ArrayList<>();
        for (int i = 1; i <= 7; i++) {
            Date d = DateUtil.offset(now, DateField.DAY_OF_MONTH, i);
            String date = DateUtil.format(d, "yyyy-MM-dd");
            Boolean tag = false;
            for (EntityMap entityMap : list3) {
                Date saleDate = entityMap.get("userTime");
                if (date.equals(saleDate.toString())) {
                    Long num = entityMap.get("userNum");
                    user_nums.add(num.intValue());
                    tag = true;
                }
            }
            if (!tag) {
                user_nums.add(0);
            }
        }
        String date = DateUtil.format(DateUtil.beginOfYear(DateUtil.date()), "yyyy-MM-dd");
        List<EntityMap> yearSaleList = orderService.getYearSale(date);
        List<BigDecimal> year_amounts = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            Boolean tag2 = false;
            for (EntityMap entityMap : yearSaleList) {
                Integer m = entityMap.get("m");
                if (m.equals(i)) {
                    year_amounts.add(entityMap.get("orderAmount"));
                    tag2 = true;
                }
            }
            if (!tag2) {
                year_amounts.add(new BigDecimal("0"));
            }
        }
        List<String> orderList = orderService.getCharge(null, null);
        PqGrid examList = examinationService.selectIndex(new PagerInfo());
        Integer courseCount=cataLogService.count();
        Integer lectureCount=lecturerService.count();
        map.put("courseCount", courseCount);
        map.put("lectureCount", lectureCount);
        map.put("year_amounts", year_amounts);
        map.put("user_nums", user_nums);
        map.put("sale_dates", sale_dates);
        map.put("sale_nums", sale_nums);
        map.put("sale_amounts", sale_amounts);
        map.put("orderList", orderList);
        map.put("examList", examList);
        return ResultBody.success(map);
    }

    /**
     * 考试统计
     */
    @PostMapping("/home/searchExam")
    public ResultBody searchExam(PagerInfo pagerInfo){
        PqGrid examList = examinationService.selectIndex(pagerInfo);
        return ResultBody.success(examList);
    }

    /**
     * 订单统计
     */
    @PostMapping("/home/searchOrder")
    public ResultBody searchOrder(String type, String beginTime, String endTime){
        Map<String, Object> map = new HashMap<>();
        if(ObjectUtils.isNotEmpty(type)){
            if(type.equals("today")){
                beginTime = DateUtil.today() + " 00:00:01";
                endTime = DateUtil.today() + " 59:59:59";
            }
            if(type.equals("yesterday")){
                beginTime = DateUtil.yesterday().toString().substring(0,10) + " 00:00:01";
                endTime = DateUtil.yesterday().toString().substring(0,10) + " 59:59:59";
            }
            if(type.equals("all")){
                beginTime = null;
                endTime = null;
            }
        }
        List<String> orderList = orderService.getCharge(beginTime, endTime);
        map.put("orderList", orderList);
        return ResultBody.success(map);
    }



}
